async function createToken(payload) {
    // 1. 头部
    const HEADER = JSON.stringify({ alg: "HS256", typ: "JWT" });
    const base64Header = base64UrlEncode(new TextEncoder().encode(HEADER));

    // 2. 载荷
    const payloadJson = JSON.stringify(payload);
    const base64Payload = base64UrlEncode(new TextEncoder().encode(payloadJson));

    // 3. 签名
    const input = `${base64Header}.${base64Payload}`;
    const sign = await signature(input, KEY, "HS256");

    // 4. 拼接
    return `${base64Header}.${base64Payload}.${sign}`;
}

const KEY = "archi_zhuzi"; // 密钥

async function signature(input, key, alg = 'HS256') {
    if (alg !== 'HS256') {
        throw new Error('Unsupported algorithm: ' + alg);
    }

    const encoder = new TextEncoder();
    const keyData = encoder.encode(key);

    const cryptoKey = await crypto.subtle.importKey(
        'raw',
        keyData,
        { name: 'HMAC', hash: { name: 'SHA-256' } },
        false,
        ['sign']
    );

    const signatureBytes = await crypto.subtle.sign(
        'HMAC',
        cryptoKey,
        encoder.encode(input)
    );

    return base64UrlEncode(new Uint8Array(signatureBytes));
}

function base64UrlEncode(input) {
    const binaryString = String.fromCharCode(...input);
    let base64String = btoa(binaryString);
    base64String = base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    return base64String;
}

let tokenStr = await createToken({
    id: '823369',
    iss:'823369',
})

console.log(tokenStr)
